package com.fanghuaiming.test.netty.c5;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

/****
 * @description:
 * @version:1.0.0
 * @author fanghuaiming
 * @data Created in 2021/9/26 下午8:50
 *
 */
public class HelloServer {

  public static void main(String[] args) {
    //1.启动器,负责组装 netty 组件,启动服务器
    new ServerBootstrap()
        //2.BossEventLoop WorkerEventLoop(简单理解一个selector,一个thread)
        .group(new NioEventLoopGroup()) //accept read 等等事件就到了new StringDecoder()等等handler
            //3.选择服务器的 NioServerSocketChannel 实现
        .channel(NioServerSocketChannel.class)
            //4.boss处理连接 worker(child)负责读写将来做什么样的业务处理
        .childHandler( //只有在accept连接建立后会触发这里面的代码
                //5.代表和客户端进行数据读写的通道 Initializer 初始化,负责添加别的handler
            new ChannelInitializer<NioSocketChannel>() {
              @Override
              protected void initChannel(NioSocketChannel ch) throws Exception {
                  //6.添加具体的 handler
                ch.pipeline().addLast(new StringDecoder());//将ByteBuf转换为字符串
                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {//自定义 handler
                            //读事件
                          @Override
                          public void channelRead(ChannelHandlerContext ctx, Object msg)
                              throws Exception {
                              System.out.println(msg);
                          }
                        });
              }
            })
            //7.绑定的监听端口
        .bind(8080);
  }
}
